package com.zqc.filter;

import com.zqc.remote.UserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * token验证拦截：用户微服务的token验证接口
 */
@Slf4j
@Component
@Order(0)
public class TokenFilter implements GlobalFilter {

    @Autowired
    private UserService userService;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("  TokenFilter...");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();
        if (path.startsWith("/api/user") || path.startsWith("/api/code")) {
            return chain.filter(exchange);
        } else {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            String token = "";
            if (cookies.containsKey("token")) {
                token = cookies.getFirst("token").getValue();
                if (token != null && !token.isEmpty()) {
                    String email = userService.info(token);
                    if (email != null && !"".equals(email)) {
                        return chain.filter(exchange);
                    }
                }
            }

            log.info("token is empty...");
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            response.getHeaders().add("Location", "/login.html");
            return response.setComplete();
        }
    }
}
